package com.example.farmer.Database;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.example.farmer.Entity.ChatMessage;

import java.util.ArrayList;
import java.util.List;

public class ChatMessageDatabase extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "chat.db";
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_CHAT = "chat";
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_PRODUCT_ID = "product_id";
    private static final String COLUMN_SENDER = "sender";
    private static final String COLUMN_RECIPIENT = "recipient";
    private static final String COLUMN_MESSAGE_CONTENT = "message_content";
    private static final String COLUMN_TIMESTAMP = "timestamp";
    private static final String COLUMN_IS_READ = "is_read";
    private static final String COLUMN_NUMBER = "userNumber";

    private static final String CREATE_TABLE_CHAT =
            "CREATE TABLE " + TABLE_CHAT + " ("
                    + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                    + COLUMN_PRODUCT_ID + " INTEGER NOT NULL,"
                    + COLUMN_SENDER + " TEXT NOT NULL,"
                    + COLUMN_RECIPIENT + " TEXT NOT NULL,"
                    + COLUMN_MESSAGE_CONTENT + " TEXT NOT NULL,"
                    + COLUMN_TIMESTAMP + " DATETIME DEFAULT CURRENT_TIMESTAMP,"
                    + COLUMN_IS_READ + " BOOLEAN DEFAULT FALSE,"
                    + COLUMN_NUMBER + " TEXT NOT NULL"
                    + ")";

    public ChatMessageDatabase(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_CHAT);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CHAT);
        onCreate(db);
    }

    // Add methods to insert and query chat messages
//插入信息
    public long insertChatMessage(ChatMessage chatMessage) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_PRODUCT_ID, chatMessage.getProductId());
        values.put(COLUMN_SENDER, chatMessage.getSender());
        values.put(COLUMN_RECIPIENT, chatMessage.getRecipient());
        values.put(COLUMN_MESSAGE_CONTENT, chatMessage.getMessageContent());
        values.put(COLUMN_IS_READ, chatMessage.isRead());
        values.put(COLUMN_NUMBER, (chatMessage.getUserNumber() != null) ? chatMessage.getUserNumber() : "defaultUserNumber"); // 使用默认值

        long result = db.insert(TABLE_CHAT, null, values);
        return result;
    }

    @SuppressLint("Range")
    public List<ChatMessage> loadChatMessagesFromDatabase(int productId) {
        List<ChatMessage> chatMessages = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_CHAT + " WHERE " + COLUMN_PRODUCT_ID + " = ?", new String[]{String.valueOf(productId)});

        if (cursor.moveToFirst()) {
            do {
                int id = cursor.getInt(cursor.getColumnIndex(COLUMN_ID));
                String sender = cursor.getString(cursor.getColumnIndex(COLUMN_SENDER));
                String recipient = cursor.getString(cursor.getColumnIndex(COLUMN_RECIPIENT));
                String messageContent = cursor.getString(cursor.getColumnIndex(COLUMN_MESSAGE_CONTENT));
                long timestamp = cursor.getLong(cursor.getColumnIndex(COLUMN_TIMESTAMP));
                boolean isRead = cursor.getInt(cursor.getColumnIndex(COLUMN_IS_READ)) != 0;


                ChatMessage message = new ChatMessage(id, productId,sender,recipient, messageContent, timestamp, isRead);
                chatMessages.add(message);
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();

        return chatMessages;
    }


    public List<ChatMessage> loadMessagesBySender(String sender) {
        List<ChatMessage> chatMessages = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();
        String[] columns = {
                COLUMN_ID, COLUMN_PRODUCT_ID, COLUMN_SENDER, COLUMN_RECIPIENT,
                COLUMN_MESSAGE_CONTENT, COLUMN_TIMESTAMP, COLUMN_IS_READ
        };
        String selection = COLUMN_SENDER + "=?";
        String[] selectionArgs = {sender};

        Cursor cursor = null;
        try {
            cursor = db.query(TABLE_CHAT, columns, selection, selectionArgs, null, null, null);
            if (cursor.moveToFirst()) {
                do {
                    int id = cursor.getInt(cursor.getColumnIndex(COLUMN_ID));
                    int productId = cursor.getInt(cursor.getColumnIndex(COLUMN_PRODUCT_ID));
                    String recipient = cursor.getString(cursor.getColumnIndex(COLUMN_RECIPIENT));
                    String messageContent = cursor.getString(cursor.getColumnIndex(COLUMN_MESSAGE_CONTENT));
                    long timestamp = cursor.getLong(cursor.getColumnIndex(COLUMN_TIMESTAMP));
                    boolean isRead = cursor.getInt(cursor.getColumnIndex(COLUMN_IS_READ)) != 0;

                    ChatMessage message = new ChatMessage(
                            id, productId, sender, recipient, messageContent, timestamp, isRead);
                    chatMessages.add(message);
                } while (cursor.moveToNext());
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            db.close();
        }
        return chatMessages;
    }


    public List<ChatMessage> loadMessagesForRecipient(String recipientUserNumber) {
        List<ChatMessage> chatMessages = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();
        String[] columns = {COLUMN_ID, COLUMN_SENDER, COLUMN_MESSAGE_CONTENT, COLUMN_TIMESTAMP, COLUMN_IS_READ};
        String selection = COLUMN_RECIPIENT + "=?";
        String[] selectionArgs = {recipientUserNumber};

        Cursor cursor = db.query(TABLE_CHAT, columns, selection, selectionArgs, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                int id = cursor.getInt(cursor.getColumnIndex(COLUMN_ID));
                String sender = cursor.getString(cursor.getColumnIndex(COLUMN_SENDER));
                String messageContent = cursor.getString(cursor.getColumnIndex(COLUMN_MESSAGE_CONTENT));
                long timestamp = cursor.getLong(cursor.getColumnIndex(COLUMN_TIMESTAMP));
                boolean isRead = cursor.getInt(cursor.getColumnIndex(COLUMN_IS_READ)) == 1;

                ChatMessage chatMessage = new ChatMessage(id, sender, messageContent, timestamp, isRead);
                chatMessages.add(chatMessage);
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return chatMessages;
    }

}